package com.atguigu.srb.core.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.srb.core.listener.ExcelDictDTOListener;
import com.atguigu.srb.core.mapper.DictMapper;
import com.atguigu.srb.core.pojo.dto.ExcelDictDTO;
import com.atguigu.srb.core.pojo.entity.Dict;
import com.atguigu.srb.core.service.DictService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 数据字典 服务实现类
 * </p>
 *
 * @author grq
 * @since 2021-04-27
 */
@Slf4j
@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    RedisTemplate redisTemplate;
    @Resource
    private DictMapper dictMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importData(InputStream inputStream) {
        EasyExcel.read(inputStream, ExcelDictDTO.class,
                new ExcelDictDTOListener(dictMapper))
                .sheet().doRead();
        log.info("导入成功");

    }

    @Override
    public List<ExcelDictDTO> listDictData() {
        final List<Dict> dictList = baseMapper.selectList(null);
        //ExcelDictDTO
        ArrayList<ExcelDictDTO> excelDictDTOS = new ArrayList<>(dictList.size());
        dictList.forEach(dict -> {
            final ExcelDictDTO excelDictDTO = new ExcelDictDTO();
            BeanUtils.copyProperties(dict, excelDictDTO);
            excelDictDTOS.add(excelDictDTO);
        });
        return excelDictDTOS;
    }

    @Override
    public List<Dict> listByParentId(Long parentId) {

        try {
            List<Dict> dictList = (List<Dict>) redisTemplate.opsForValue().get("srb:core:dicList:" + parentId);
            if (CollectionUtils.isNotEmpty(dictList)) {
                return dictList;
            }
        } catch (Exception e) {
            log.error("redis服务器异常{}", ExceptionUtils.getStackTrace(e));
        }

        final QueryWrapper<Dict>
                queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        final List<Dict> dicts = baseMapper.selectList(queryWrapper);
        dicts.forEach(dict -> {
            //判断是否有子节点，找到当前的dict 下级 有没有子节点
            dict.setHasChildren(this.hasChildren(dict.getId()));
        });

        try {
            //将数据存入Redis
            redisTemplate.opsForValue().set("srb:core:dicList:" + parentId, dicts);
        } catch (Exception e) {
            log.error("redis服务器异常{}", ExceptionUtils.getStackTrace(e));
        }
        return dicts;
    }

    /**
     * 判断该节点是否有子节点
     */
    private boolean hasChildren(Long id) {
        QueryWrapper<Dict> queryWrapper = new QueryWrapper<Dict>().eq("parent_id", id);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count.intValue() > 0) {
            return true;
        }
        return false;
    }
}
